package com.hj.security.ui;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.hj.security.R;
import com.hj.security.engine.DownloadTask;
import com.hj.security.engine.SmsService;
import com.hj.security.service.AddressService;
import com.hj.security.service.BackupSmsService;

public class AToolActivity extends Activity implements OnClickListener{

	protected static final int SUCCESS = 0;
	protected static final int ERROR = 1;
	
	private TextView tv_atool_query;
	private TextView tv_atool_number_service_state;
	private CheckBox cb_atool_state;
	private TextView tv_atool_select_bg;
	private TextView tv_atool_change_location;
	private TextView tv_atool_number_security;
	private TextView tv_atool_app_lock;
	private TextView tv_atool_common_number;
	private Intent serviceIntent;
	private ProgressDialog progressDialog;
	
	private SharedPreferences sp;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case ERROR:
				Toast.makeText(AToolActivity.this, "下载通讯数据库失败，请检查网络！", Toast.LENGTH_SHORT).show();
				break;
			case SUCCESS:
				Toast.makeText(AToolActivity.this, "通讯数据库下载成功！", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.atool);
		tv_atool_query = (TextView) findViewById(R.id.tv_atool_query);
		tv_atool_query.setOnClickListener(this);
		
		tv_atool_change_location = (TextView) findViewById(R.id.tv_atool_change_location);
		tv_atool_change_location.setOnClickListener(this);
		
		tv_atool_select_bg = (TextView) findViewById(R.id.tv_atool_select_bg);
		tv_atool_select_bg.setOnClickListener(this);
		
		tv_atool_number_security = (TextView) findViewById(R.id.tv_atool_number_security);
		tv_atool_number_security.setOnClickListener(this);
		
		tv_atool_number_service_state = (TextView) findViewById(R.id.tv_atool_number_service_state);
		cb_atool_state = (CheckBox) findViewById(R.id.cb_atool_state);
		
		tv_atool_app_lock = (TextView) findViewById(R.id.tv_atool_app_lock);
		tv_atool_app_lock.setOnClickListener(this);
		
		tv_atool_common_number = (TextView) findViewById(R.id.tv_atool_common_number);
		tv_atool_common_number.setOnClickListener(this);
		
		cb_atool_state.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					tv_atool_number_service_state.setText("归属地服务已开启");
					serviceIntent = new Intent(AToolActivity.this, AddressService.class);
					startService(serviceIntent);
				}else{
					tv_atool_number_service_state.setText("归属地服务未开启");
					stopService(serviceIntent);
				}
			}
		});
		
		sp = this.getSharedPreferences("config", Context.MODE_PRIVATE);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_atool_query:
			query();
			break;
		case R.id.tv_atool_select_bg:
			selectStyle();
			break;
		case R.id.tv_atool_change_location:
			Intent dvIntent = new Intent(this, DragViewActiivty.class);
			startActivity(dvIntent);
			break;
		case R.id.tv_atool_number_security:
			Intent nsIntent = new Intent(this, NumberSecurityActivity.class);
			startActivity(nsIntent);	
			break;
		case R.id.tv_atool_sms_backup:
			Intent sbIntent = new Intent(this, BackupSmsService.class);
			startService(sbIntent);	
			break;
		case R.id.tv_atool_sms_restore:
			Intent srIntent = new Intent(this, NumberSecurityActivity.class);
			startActivity(srIntent);	
			break;
		case R.id.tv_atool_app_lock:
			Intent alIntent = new Intent(this, AppLockActivity.class);
			startActivity(alIntent);
		case R.id.tv_atool_common_number:
			Intent acIntent = new Intent(this, CommonNumberActivity.class);
			startActivity(acIntent);
		default:
			break;
		}
	}

	private void query() {
		if(isDBExist()){
			Intent intent = new Intent(this, QueryNumberActivity.class);
			startActivity(intent);				
		}else{
			//提示用户下载数据库
			progressDialog = new ProgressDialog(this);
			progressDialog.setMessage("正在下载数据库");
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setCancelable(true);
			progressDialog.show();
			new Thread(){
				@Override
				public void run() {
					String path = getResources().getString(R.string.serverdb);
					File dir = new File(Environment.getExternalStorageDirectory()+"/security/db");
					if(!dir.exists()){
						dir.mkdirs();
					}
					String dbPath = Environment.getExternalStorageDirectory()+"/security/db/data.db";
					try {
						DownloadTask.getFile(path, dbPath, progressDialog);
						progressDialog.dismiss();
					} catch (Exception e) {
						e.printStackTrace();
						progressDialog.dismiss();
						Message message = new Message();
						message.what=ERROR;
						handler.sendMessage(message);
					}
				}
			}.start();
		}
	}
	private boolean isDBExist() {
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			File file = new File(Environment.getExternalStorageDirectory()+"/security/db/data.db");
			if(file.exists()){
				return true;
			}
		}
		return false;
	}
	private void selectStyle(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("归属地显示风格");
		String[] items = new String[]{"半透明", "活力橙", "苹果绿", "孔雀蓝", "金属灰"};
		builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Editor editor = sp.edit();
				editor.putInt("background", which);
				editor.commit();
			}
		});
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
		builder.show();
	}
	
	private void restore(){
		final ProgressDialog pd = new ProgressDialog(this);
		pd.setTitle("还原短信");
		pd.setMessage("正在还原短信");
		pd.setCancelable(false);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.show();
		final SmsService smsService = new SmsService(this);
		new Thread(){
			public void run() {
				try {
					smsService.restore(Environment.getExternalStorageDirectory()+"/security/backup/smsbackup.xml", pd);
					pd.dismiss();
					Looper.prepare();//创建一个Looper  
					Toast.makeText(getApplicationContext(), "还原成功", Toast.LENGTH_LONG);
					Looper.loop();//轮循一次Looper  
				} catch (Exception e) {
					e.printStackTrace();
					Looper.prepare();//创建一个Looper
					Toast.makeText(getApplicationContext(), "还原失败", Toast.LENGTH_LONG);
					Looper.loop();//轮循一次Loope
				}
			};
		}.start();
	}
}
